package com.sfac.springCloudAccount.dao;


import org.apache.ibatis.annotations.*;
import org.example.account.entity.User;
import org.example.common.vo.Search;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author jzq
 * @date 2022/8/26 20:04
 */
@SuppressWarnings({"all"})
@Mapper
@Repository
public interface UserDao {

    @Select("select * from account_user where user_name = #{userName} and password = #{password}")
    User getUserByUserNameAndPassword(@Param("userName") String userName, @Param("password") String password);

    @Select("select * from account_user where email = #{email} or user_name = #{userName}")
    List<User> getUserByUserNameOrEmail(@Param("email") String email, @Param("userName") String userName);

    @Select("select * from account_user where user_name = #{userName}")
    List<User> getUserByUserName(String userName);

    @Insert("insert into account_user (email, user_name, password, user_image, create_date) "
            + "values (#{email}, #{userName}, #{password}, #{userImage}, #{createDate})")
    @Options(useGeneratedKeys = true, keyColumn = "id", keyProperty = "id")
    void insertUser(User user);

    @Update("update account_user set email = #{email}, user_name = #{userName}, "
            + "user_image = #{userImage} where id = #{id}")
    void updateUser(User user);

    @Update("update account_user set password = #{password} where id = ${id}")
    void updateUserPassword(@Param("password") String password, @Param("id") int id);

    @Select("select * from account_user where id = #{id}")
    @Results(id="userResult", value={
            @Result(column="id", property="id"),
            @Result(column="id",property="roles",
                    javaType=List.class,
                    many=@Many(select="com.sfac.springCloudAccount.dao.RoleDao.getRolesByUserId"))
    })
    User getUserById(int id);

    @Delete("delete from account_user where id = #{id}")
    void deleteUserById(int id);

    @Select("<script>"
            + "select * from account_user "
            + "<where> "
            + "<if test='keyword != \"\" and keyword != null'>"
            + " and (email like '%${keyword}%' or "
            + " user_name like '%${keyword}%') "
            + "</if>"
            + "</where>"
            + "<choose>"
            + "<when test='sort != \"\" and sort != null'>"
            + " order by ${sort} ${direction}"
            + "</when>"
            + "<otherwise>"
            + " order by id desc"
            + "</otherwise>"
            + "</choose>"
            + "</script>")
    List<User> getUsersBySearchVo(Search search);

}

